package edu.mcw.rgd.clinminer.web.utils;

import com.vaadin.ui.Component;
import com.vaadin.ui.DefaultFieldFactory;
import com.vaadin.ui.Field;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.vaadin.addon.jpacontainer.JPAContainer;
import com.vaadin.data.Item;

import edu.mcw.rgd.clinminer.domain.Participant;
import edu.mcw.rgd.clinminer.web.EntityProviderUtil;

/**
 * Factory pattern for uniform creation of input fields across the whole
 * application
 *
 * @author Tomasz Adamusiak <tadamusiak@mcw.edu>
 *
 */
public class ClinminerFormFieldFactory extends DefaultFieldFactory {
	private static final Logger log = Logger
			.getLogger(ClinminerFormFieldFactory.class);
	private Map<String, FieldConfiguration> map;
	private JPAContainer<Participant> containerForParticipants;

	public ClinminerFormFieldFactory() {
		// map enum keys for easier retrieval
		map = new HashMap<String, FieldConfiguration>();
		for (FieldConfiguration fieldType : FieldConfiguration.values()) {
			map.put(fieldType.toString(), fieldType);
		}
	}

	@Override
	public Field createField(Item item, Object propertyId, Component uiContext) {
		Field field = null;

		if (!map.containsKey(propertyId)) {
			log.warn("No appropriate field configuration found for "
					+ propertyId + ". Falling back to default");
			return super.createField(item, propertyId, uiContext);
		}

		field = map.get(propertyId).create();

		return field;
	}

	public JPAContainer<Participant> getContainerForParticipants() {
		if (containerForParticipants == null) {
			JPAContainer<Participant> container = new JPAContainer<Participant>(
					Participant.class);
			container.setEntityProvider(EntityProviderUtil.get()
					.getEntityProvider(Participant.class));
			containerForParticipants = container;
		}
		return containerForParticipants;
	}

}
